<?php
namespace Extend\Controller;

/**
 * 房卡相关rpc接口
 * @modify trainyao 2016-05-11 创建
 */
class CardController extends ParentController {
    protected function _initialize() {
        $this->validateUtil = new \Org\Util\Validate();
    }

    /**
     * 获取用户有效订单或历史订单
     * @modify trainyao 2016-01-11    创建
     * @modify wenhui 2017-02-23    增加返回字段 orderRoomId bookUserId
     * @modify wenhui 2017-02-23    增加返回字段 price  orderNumber
     * @param intetger $userId 预定用户ID
     * @param intetger $status 0=有效订单,1=历史订单
     */
    public function item($data) {
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }
        $userId = $data['userId'];

        // 取出用户所有的订单
        $bookCardLogic = A('Common/BookCard', 'Logic');
        try {
            $cardInfo = $bookCardLogic->getCard($userId);
        } catch (\Exception $e) {
            return parent::returnJson($e->getMessage());
        }

        if (empty($cardInfo)) {
            return parent::returnJson(200, 200, array());
        }

        $orderRoomModel = D('OrderRoom');
        foreach ($cardInfo as &$cardInfoItem) {
            // 获取订单金额
            $orderRoomInfo = $orderRoomModel->getInfoByOrder($cardInfoItem['orderRoom']['orderinfo_id'], false);
            foreach ($orderRoomInfo as $key => $orderRoomInfoItme) {
               $cardInfoItem['price'] += (double)$orderRoomInfoItme['payment']; 
            }
            unset($orderRoomInfoItme);

            $cardInfoItem['orderNumber'] = encodeOrderNumber($cardInfoItem['orderroom_id'], 'MZ');
            $cardInfoItem['orderRoomId'] = $cardInfoItem['orderroom_id'];
            $cardInfoItem['bookUserId'] = $userId;
            $cardInfoItem['startDate'] = $cardInfoItem['startdate'];
            $cardInfoItem['endDate'] = $cardInfoItem['enddate'];
            $cardInfoItem['hotelName'] = $cardInfoItem['hotelDetail']['name'];
            $cardInfoItem['hotel'] = $cardInfoItem['hotelDetail']['hotelentity_id'];
            $cardInfoItem['roomTypeName'] = $cardInfoItem['orderRoom']['roomtype_name'];
            $cardInfoItem['roomName'] = $cardInfoItem['orderRoom']['roominfo_name'];
            unset($cardInfoItem['id']);
            unset($cardInfoItem['userlogin_id']);
            unset($cardInfoItem['orderroom_id']);
            unset($cardInfoItem['orderuser_id']);
            unset($cardInfoItem['startdate']);
            unset($cardInfoItem['enddate']);
            unset($cardInfoItem['roomtype_name']);
            unset($cardInfoItem['roominfo_name']);
            unset($cardInfoItem['isdelete']);
            unset($cardInfoItem['orderRoom']);
            unset($cardInfoItem['hotelDetail']);
            unset($cardInfoItem['roominfo_id']);
            unset($cardInfoItem['roomInfo']);
        }
        unset($cardInfoItem);

        return parent::returnJson(200, 200, array_values($cardInfo));
    }

    /**
     * 获取房卡RPC接口
     * @modify trainyao 2016-05-17 创建
     * @modify wenhui 2017-02-20 修改 以子订单id获取房卡
     * @modify wenhui 2017-03-8 抛异常 添加telephone 前台电话
     * @param  array   $data      RPC传入数据
     * @return array              data{
     *                                hotelName: 客栈名称
     *                                roomTypeName: 房型名称
     *                                roomName: 房间名称
     *                                cardString: 二维码字符串
     *                            }
     */
    public function detail($data) {
        parent::switchTimeUtc($data);
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $validateRule = array(
            'bookUserId' => 'notnull,notempty,id',
            'orderRoomId' => 'notnull,notempty,id',
        );
        $validatePass = $this->validateUtil->validate($data, $validateRule);
        if (empty($validatePass)) {
            $message = $this->validateUtil->getError('explode', ',');
            return parent::returnJson($message['msg'][0], $message['msg'][1]);
        }

        $userId = $data['userId'];
        //$orderRoomId = decodeOrderNumber($data['orderNumber'], 'MZ');
        $bookUserId = $data['bookUserId'];
        $orderRoomId = $data['orderRoomId'];
        $hotel = $data['hotel'];

        $orderRoomModel = D('OrderRoom');
        $roomInfoModel = D('RoomInfo');
        $orderRoomInfo = $orderRoomModel->getInfo($orderRoomId);
        $roomInfo = $roomInfoModel->getInfo($orderRoomInfo[0]['roominfo_id']);
        // 是否是RF卡
        if ($roomInfo['roomfrom'] == ROOMFROM_RF || $roomInfo['roomfrom'] == ROOMFROM_OTHER) {
            return parent::returnJson(403, 606);
        }

        // 取出订单信息,检查是否已入住,操作人是否入住人
        $bookCardLogic = A('Common/bookCard', 'Logic');
        try {
            $cardDetail = $bookCardLogic->checkCanGetCard($orderRoomId, $bookUserId);
            $keys = array_keys($cardDetail);
            if($keys == array_keys($keys))
            {
                $cardDetail = $cardDetail[0];
            }
        } catch (\Exception $e) {
            if ($e->getMessage() == '403,602') {
                $hotelDetailModel = D('HotelDetail');
                $hotelDetailInfo = $hotelDetailModel->getInfoByHotels($hotel);
                if (isset($hotelDetailInfo[0]['telephone']) && !empty($hotelDetailInfo[0]['telephone'])) {
                    $telephone = $hotelDetailInfo[0]['telephone'];
                } else {
                    $telephone = $hotelDetailInfo[0]['mobile'];
                }
                return parent::returnJson($e->getMessage(), null, $telephone);
            } else {
                return parent::returnJson($e->getMessage());
            }

        }

        // 调用RPC获取房卡
        $hotelEntityModel = D('HotelEntity');
        $hotelInfo = $hotelEntityModel->getInfo($cardDetail['hotelDetail']['hotelentity_id'], false);

        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_QRCODE_URL'));
        $client->setEncryptMode(3);
        $data = array(
            'flag' => 'uclbrt',
            'communityNo' => $hotelInfo['communityno'],
            'room' => $cardDetail['roomInfo']['name'],
            'minute' => 5,
            'eletricTime' => $cardDetail['enddate'],
            'time' => time(),
            'userId' => $userId,
            'from' => 1,
        );
        $result = $client->getCardForMeizhu($data);
        if (!is_string($result)) {
            return parent::returnJson(403, 603);
        }
        $result = json_decode($result, true);
        if ($result['httpstatus'] != 200) {
            return parent::returnJson(403, 603);
        }

        return parent::returnJson(200, 200, array(
            'hotelName' => $cardDetail['hotelDetail']['name'],
            'roomTypeName' => $cardDetail['orderRoom']['roomtype_name'],
            'roomName' => $cardDetail['orderRoom']['roominfo_name'],
            'cardString' => $result['data'],
        ));
    }
    
    public function getCardLink($data)
    {
        parent::switchTimeUtc($data);
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $hotelId = $data['hotelId'];
        $orderRoomId = $data['orderRoomId'];
        $areaCode = $data['areaCode'];
        $mobile = $data['mobile'];
        $_SESSION[C('USER_ID')] = $data['operator'];
        $BookCardLogic = A('Common/BookCard', 'Logic');
        $card = $BookCardLogic->shareCard($hotelId, $orderRoomId, $mobile, "1", $areaCode, 1);        
        return parent::returnJson(200, 200, $card);
    }
    
    public function deleteShareCard($data)
    {
        parent::switchTimeUtc($data);
        if (empty(parent::checkRPCRight($data))) {
            return parent::returnJson(403, 202);
        }
        $orderRoomId = $data['orderRoomId'];
        $areaCode = $data['areaCode'];
        $mobile = $data['mobile'];
        $BookCardLogic = A('Common/BookCard', 'Logic');
        $result = $BookCardLogic->deleteShareCard($orderRoomId, $mobile, $areaCode);
        return parent::returnJson($result[0], $result[1], $result[2]);
    }
}
